package fm.huanxin.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fm.exception.BizException;
import io.swagger.client.api.AuthenticationApi;
import io.swagger.client.model.Token;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by CM on 17/6/2.
 */
public class TokenUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(TokenUtils.class);
    private static String ACCESS_TOKEN;
    private static Long EXPIERED_TIME;

    private static void initToken() throws Exception {
        AuthenticationApi api = new AuthenticationApi();

        Token body = new Token().clientId(OrgInfo.getClientId()).grantType(OrgInfo.getGrantType()).clientSecret(OrgInfo.getClientSecret());
        String result = api.orgNameAppNameTokenPost(OrgInfo.getOrgName(), OrgInfo.getAppName(), body);

        if (StringUtils.isNotEmpty(result)) {
            JSONObject object = JSON.parseObject(result);
            ACCESS_TOKEN = " Bearer " + object.get("access_token");
            EXPIERED_TIME = System.currentTimeMillis() + object.getInteger("expires_in");
            LOGGER.info("更新AccessToken:{},过期时间:{}", ACCESS_TOKEN, EXPIERED_TIME);
        } else {
            throw new BizException("初始化access token失败,服务器返回空值");
        }
    }

    public static String getAccessToken() throws Exception {
        if (StringUtils.isEmpty(ACCESS_TOKEN) || isExpired()) {
            initToken();
        }
        return ACCESS_TOKEN;
    }

    private static boolean isExpired() {
        if (EXPIERED_TIME == null) {
            return true;
        }
        return System.currentTimeMillis() > EXPIERED_TIME-5;
    }

}
